const { merge } = require('webpack-merge');
const config = require('./webpack.config.js');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const path = require('path');
const TerserPlugin = require('terser-webpack-plugin');

module.exports = merge(config, {
  mode: 'production',
  devtool: 'source-map',
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].css',
      chunkFilename: '[id].css',
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
      {
        test: /\.less$/i,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader', //注意css-loader版本，否则会导致cssModule报错，例如找不到类名之类的
            options: {
              modules: {
                localIdentName: '[name]__[local]___[hash:base64:5]', // 自定义类名格式
                auto: true,
              },
            },
          },
          {
            loader: 'postcss-loader',
            options: {
              postcssOptions: {
                // plugins: [require('autoprefixer'), require('tailwindcss')],
                plugins: [require('autoprefixer')()],
              },
            },
          },
          {
            loader: 'less-loader', // 编译Less到CSS
            options: {
              lessOptions: {
                // paths: [path.resolve(__dirname, 'node_modules')],
                javascriptEnabled: true, // 启用内联JavaScript
              },
            },
          },
        ],
      },
    ],
  },
  optimization: {
    minimize: true,
    removeAvailableModules: true,
    removeEmptyChunks: true,
    sideEffects: true,
    runtimeChunk: 'single',
    splitChunks: {
      chunks: 'all', // 分割所有类型的chunks
      minSize: 30000, // 最小模块大小
      maxSize: 500000, // 最大模块大小
      minChunks: 1, // 最小chunks数量
      maxAsyncRequests: 30,
      maxInitialRequests: 30,
      enforceSizeThreshold: 50000,
      cacheGroups: {
        defaultVendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10,
          reuseExistingChunk: true,
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true,
        },
      },
    },
    minimizer: [
      // 在 webpack@5 中，你可以使用 `...` 语法来扩展现有的 minimizer（即 `terser-webpack-plugin`），将下一行取消注释
      `...`,
      new TerserPlugin({
        terserOptions: {
          compress: {
            drop_console: true, // 移除所有的console调用
          },
        },
      }),
      new CssMinimizerPlugin({
        minimizerOptions: {
          preset: [
            'default',
            {
              discardComments: { removeAll: true },
            },
          ],
        },
      }),
    ],
  },
  // devtool: false, // 是否开启源码映射：false、'source-map'
});
